﻿using Inovout.Component;
using Inovout.Data.Service;
using Inovout.Organization.Domain;
using Inovout.People.Domain;
using KuaJing.ManagementConsole.WebPage.Service_263;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Xml.Linq;

namespace Inovout.Cloud.Messager.WebPage.Models
{
    public class PersonLogic : RepositoryService<Person>
    {
        private readonly string userid;
        private readonly string key;
        private readonly string domain;
        private readonly string account;
        public PersonLogic()
        {
            userid = ConfigurationManager.AppSettings["userid"];
            key = ConfigurationManager.AppSettings["key"];
            domain = ConfigurationManager.AppSettings["domain"];
            account = ConfigurationManager.AppSettings["account"];
        }
        /// <summary>
        /// 引用WebService，读取人员信息
        /// </summary>
        /// <returns></returns>
        public string GetPersonData()
        {
            XmapiImplService service = new XmapiImplService();
            string sign = Md5Sign(domain + account + key);
            string str = service.getDomainUserlist_New(domain, account, sign);
            return str;
        }
        /// <summary>
        /// 32位 小写 MD5 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string Md5Sign(string str)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] buffer = Encoding.Default.GetBytes(str);
            string result = BitConverter.ToString(md5.ComputeHash(buffer));
            return result.Replace("-", "").ToLower();
        }

        public void Handle()
        {
            MembershipUserLogic userlogic=new MembershipUserLogic();
            ContactLogic contactlogic = new ContactLogic();
            EmployeeLogic employeelogic = new EmployeeLogic();
            PositionLogic positionlogic = new PositionLogic();
            PersonMembershipLogic shiplogic = new PersonMembershipLogic();
            DepartmentLogic departmentlogic = new DepartmentLogic();
            List<OrganizationUnit> departments = departmentlogic.GetAllDepaetment();
            List<Persondata> dPersons = GetALLPerson(GetPersonData());
            List<Persondata> Persons = new List<Persondata>();
            foreach (OrganizationUnit department in departments)
            {
                List<Persondata> PersonDatas = dPersons.Where(c => c.departmentid == department.DepartmentId && c.mobile.Length==11).Select(c => c).ToList();
                foreach(Persondata data in PersonDatas)
                {
                    Persons.Add(data);
                }
            }
            List<Person> Units = GetAllPerson();
            foreach (Persondata person in Persons)
            {
                if (Units.Count() == 0)
                {
                    Person ships = new Person();
                    ships.UserId = person.userid;
                    ships.OrganizationUnitId = person.departmentid;
                    ships.Name = person.name;
                    InsertPerson(ships);
                }
                else
                {
                    Person ship = Units.Where(c => c.UserId.Equals(person.userid)).Select(c => c).SingleOrDefault();
                    if (ship == null)
                    {
                        Person shipd = new Person();
                        shipd.UserId = person.userid;
                        shipd.OrganizationUnitId = person.departmentid;
                        shipd.Name = person.name;
                        InsertPerson(shipd);
                    }
                    else
                    {
                        Units.Remove(ship);
                        ship.UserId = person.userid;
                        ship.OrganizationUnitId = person.departmentid;
                        ship.Name = person.name;
                        InsertPerson(ship);
                    }
                }
            }
            RemoveAllPerson(Units);
            employeelogic.HandleEmployee();
            contactlogic.HandleContact();
            positionlogic.HandlePosition();
            shiplogic.HandlePersonMembership();

            List<Person> dtpersons = GetAllPerson();
            dtpersons.ForEach(c => { userlogic.InsertMembershipUser(c); });
            
        }
        public List<Persondata> GetALLPerson(string url)
        {
            XDocument Doc = XDocument.Parse(url);
            List<Persondata> Persons = new List<Persondata>();
            var query = (from item in Doc.Descendants("user")
                         select new
                         {
                             userId = item.Element("userid").Value,
                             name = item.Element("name") == null ? null : item.Element("name").Value,
                             domainId = item.Element("departmentid").Value,
                             office = item.Element("office") == null ? null : item.Element("office").Value,
                             mobile = item.Element("mobile") == null ? null : item.Element("mobile").Value,
                             phone = item.Element("phone") == null ? null : item.Element("phone").Value,
                             fax = item.Element("fax") == null ? null : item.Element("fax").Value
                         }).ToList();
            foreach (var item in query)
            {
                Persondata person = new Persondata();
                person.userid= item.userId;
                person.name = item.name;
                person.departmentid = item.domainId;
                person.office= item.office;
                person.mobile = item.mobile;
                person.phone = item.phone;
                person.fax = item.fax;
                Persons.Add(person);
            }
            return Persons;
        }

        /// <summary>
        /// 查询部门
        /// </summary>
        /// <param name="departmentid"></param>
        /// <returns></returns>
        public Person GetPerson(string userid)
        {
            string str = userid;
            IRepositoryService<Person> Service = ComponentRegistry.Resolve<IRepositoryService<Person>>();
            Person unit = Service.Query().SingleOrDefault(c => c.UserId.Equals(str));
            return unit;
        }
        public void InsertPerson(Person Unit)
        {
            IRepositoryService<Person> Service = ComponentRegistry.Resolve<IRepositoryService<Person>>();
            Service.Save(Unit);
        }
        public List<Person> GetAllPerson()
        {
            IRepositoryService<Person> Service = ComponentRegistry.Resolve<IRepositoryService<Person>>();
            return Service.Query().ToList();
        }
        public void RemoveAllPerson(List<Person> Persons)
        {
            IRepositoryService<Person> Service = ComponentRegistry.Resolve<IRepositoryService<Person>>();
            foreach (Person person in Persons)
            {
                Service.Delete(person);
            }
        }
        public void InsertContact(Persondata person,Person shipd)
        {
            ContactLogic contactlogic = new ContactLogic();
            if (!person.mobile.Equals(null) && !person.mobile.Equals(""))
            {
                Contact contact = new Contact();
                contact.Value = person.mobile;
                contact.Person = shipd;
                contact.Label = ContactMethod.Mobile;
                contactlogic.InsertContact(contact);
            }
            if (!person.phone.Equals(null) && !person.phone.Equals(""))
            {
                Contact contact = new Contact();
                contact.Value = person.phone;
                contact.Person = shipd;
                contact.Label = ContactMethod.Tel;
                contactlogic.InsertContact(contact);
            }
        }
    }
}